﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RabbitMQ.Client;

namespace Hong.Common.RabbitMQ
{
    public class RabbitMqConfig
    {
        /// <summary>
        /// rabbitmq生产者
        /// </summary>
        /// <param name="message">数据</param>
        /// <param name="exchange">交换机名称</param>
        /// <param name="typename">交换机类型</param>
        /// <param name="ip">ip地址</param>
        /// <param name="username">用户名</param>
        /// <param name="pwd">密码</param>
        public void RabbitMqEmitLog(string message, string exchange = "logs", string typename = "fanout", string ip = "192.168.150.1", string username = "huskie", string pwd = "123456")
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }
            var factory = new ConnectionFactory() { };
            factory.HostName = ip; //RabbitMQ服务在本地运行
            factory.UserName = username; //用户名
            factory.Password = pwd; //密码
            factory.Port = AmqpTcpEndpoint.UseDefaultPort;
            //factory.VirtualHost = "/";  //默认为"/"
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                //扇形交换机
                channel.ExchangeDeclare(exchange: exchange, type: typename);
                var body = Encoding.UTF8.GetBytes(message);

                channel.BasicPublish(exchange: "logs",
                    routingKey: "",
                    basicProperties: null,
                    body: body);
            }
        }
    }
}
